<template>
  <div class="app-container">



    <el-card shadow="always" style="margin-top: 20px;">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-row :gutter="20">
          <!-- 第一列 -->
          <el-col :span="22">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="所属方向" prop="deptId">
                  <el-select
                    v-model="queryParams.deptId"
                    placeholder="请选择所属方向"
                    clearable
                  >
                    <el-option
                      v-for="dept in deptList"
                      :key="dept.deptId"
                      :label="dept.deptName"
                      :value="dept.deptId"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="专利类型" prop="patentType" :span="4" style="margin-bottom: 15px;">
                  <el-select v-model="queryParams.patentType" placeholder="请选择专利类型" clearable>
                    <el-option
                      v-for="dict in dict.type.sci_palent_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="申请状态" prop="applicationStatus" :span="4" style="margin-bottom: 15px;">
                  <el-select v-model="queryParams.applicationStatus" placeholder="请选择申请状态" clearable>
                    <el-option
                      v-for="dict in dict.type.sci_ach_appl_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="研究院署名" prop="instituteSignature">
                  <el-select v-model="queryParams.instituteSignature" placeholder="请选择研究院署名" clearable>
                    <el-option
                      v-for="dict in dict.type.sci_signature"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>





              </el-col>
              <el-col :span="24">
                <el-form-item label="统计年度" prop="statisticalYear">
                  <el-input
                    v-model="queryParams.statisticalYear"
                    placeholder="请输入统计年度"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>

                <el-form-item label="专利名称" prop="patentName" :span="4" style="margin-bottom: 15px;">
                  <el-input
                    v-model="queryParams.patentName"
                    placeholder="请输入专利名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>

                <el-form-item label="申请人" prop="applicant">
                  <el-input
                    v-model="queryParams.applicant"
                    placeholder="请输入申请人"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>


                <el-form-item label="所属项目" prop="projectId">
                  <el-select
                    v-model="queryParams.projectId"
                    placeholder="请选择所属项目"
                    clearable
                  >
                    <el-option
                      v-for="project in projectList"
                      :key="project.id"
                      :label="project.projectName"
                      :value="project.id"
                    />
                  </el-select>
                </el-form-item>


              </el-col>
              <el-col :span="24">

                <el-form-item label="申请时间">
                  <el-date-picker
                    v-model="daterangeApplicationDate"
                    style="width: 208px"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item label="授权时间">
                  <el-date-picker
                    v-model="daterangeAuthorizationDate"
                    style="width: 208px"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <!-- 第二列 -->
          <el-col :span="2">
            <el-row>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-row>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="always" style="margin-top: 20px;">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:patent:add']"
          >新增</el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:patent:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="patentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="统计年度" width="100" align="center" prop="statisticalYear">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sci_year" :value="scope.row.statisticalYear"/>
        </template>
        </el-table-column>
        <el-table-column label="所属方向" align="center" prop="deptId">
          <template slot-scope="scope">
            {{ getDeptLabel(scope.row.deptId) }}
          </template>
        </el-table-column>
        <el-table-column label="专利名称" align="center" prop="patentName" />
        <el-table-column label="专利类型" width="100" align="center" prop="patentType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sci_palent_type" :value="scope.row.patentType"/>
          </template>
        </el-table-column>
        <el-table-column label="申请状态" width="80"align="center" prop="applicationStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sci_ach_appl_status" :value="scope.row.applicationStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="研究院署名" width="90"align="center" prop="instituteSignature">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sci_signature" :value="scope.row.instituteSignature"/>
          </template>
        </el-table-column>
        <el-table-column label="申请号" width="140"align="center" prop="applicationNumber" />
        <el-table-column label="申请人" width="70"align="center" prop="applicant" />
        <el-table-column label="申请时间" align="center" prop="applicationDate" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.applicationDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="授权时间" align="center" prop="authorizationDate" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.authorizationDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属项目" align="center" prop="projectId">

          <template slot-scope="scope">
            {{ getProjectLabel(scope.row.projectId) }}
          </template>
        </el-table-column>




<!--


        <el-table-column label="合作类型" align="center" prop="cooperationType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sci_cooperation_type" :value="scope.row.cooperationType"/>
          </template>
        </el-table-column>


        <el-table-column label="专利范围" align="center" prop="patentScope">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sci_patent_scope" :value="scope.row.patentScope"/>
          </template>
        </el-table-column>
        <el-table-column label="是否PCT专利" align="center" prop="isPct">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isPct"/>
          </template>
        </el-table-column> -->
        <el-table-column label="操作"  width="200" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              type="text"
              style="color: #409EFF;"
              @click="handleView(scope.row)"
              v-hasPermi="['system:patent:edit']"
            >查看</el-button>
            <el-button
              type="text"
              style="color: #E6A23C;"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:patent:edit']"
            >修改</el-button>
            <el-button
              type="text"
              style="color: #67C23A;"
              @click="handleStatusUpdate(scope.row)"
              v-hasPermi="['system:patent:status']"
            >状态变更</el-button>
            <el-button
              type="text"
              style="color: #F56C6C;"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:patent:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改科研专利信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-card shadow="always" style="margin-left: 20px;margin-right: 20px;">
        <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="120px">
          <el-divider ><i class="el-icon-collection"></i>  基本信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="专利名称" prop="patentName">
                <el-input v-model="form.patentName" placeholder="请输入专利名称" clearable
                  :style="{width: '100%'}"
                   maxlength="100" show-word-limit></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="研究方向" prop="deptId">
                <el-select v-model="form.deptId" placeholder="请选择所属方向" clearable :style="{width: '100%'}">
                  <el-option
                    v-for="dept in deptList"
                    :key="dept.deptId"
                    :label="dept.deptName"
                    :value="dept.deptId"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="专利类型" prop="patentType">
                <el-radio-group v-model="form.patentType" size="medium">
                  <el-radio
                    v-for="(item, index) in dict.type.sci_palent_type"
                    :key="index"
                    :label="item.value"
                    :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请人" prop="applicant">
                <el-input v-model="form.applicant" placeholder="请输入申请人" clearable :style="{width: '100%'}"
                 maxlength="100" show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="24">
              <el-form-item label="专利状态" prop="applicationStatus">
                <el-radio-group v-model="form.applicationStatus" size="medium">
                  <el-radio v-for="(item, index) in dict.type.sci_ach_appl_status" :key="index" :label="item.value"
                    :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col> -->
            <el-col :span="24">
              <el-form-item label="专利状态" prop="applicationStatus">
                <el-radio-group v-model="form.applicationStatus" size="medium" >
                  <el-radio v-for="(status, index) in availableStatuses" :key="index" :label="status"
                  :disabled="!isAdding" >{{status}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="专利申请号" prop="applicationNumber">
                <el-input v-model="form.applicationNumber" placeholder="请输入专利申请号" clearable
                  :style="{width: '100%'}" maxlength="50"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请时间" prop="applicationDate">
                <el-date-picker v-model="form.applicationDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  :style="{width: '100%'}" placeholder="请输入申请时间" clearable></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider ><i class="el-icon-postcard"></i>  详细信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合作类型" prop="cooperationType">
                <el-radio-group v-model="form.cooperationType" size="medium">
                  <el-radio v-for="(item, index) in dict.type.sci_cooperation_type" :key="index" :label="item.value"
                    :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="授权时间" prop="authorizationDate">
                <el-date-picker v-model="form.authorizationDate" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请输入授权时间" clearable>
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="统计年度" prop="statisticalYear">
                <el-select v-model="form.statisticalYear" placeholder="请输入统计年度" clearable
                  :style="{width: '100%'}">
                  <el-option v-for="(item, index) in statisticalYearOptions" :key="index" :label="item.label"
                    :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="研究院署名" prop="instituteSignature">
                <el-radio-group v-model="form.instituteSignature" size="medium">
                  <el-radio v-for="(item, index) in dict.type.sci_signature" :key="index" :label="item.value"
                    :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="专利范围" prop="patentScope">
                <el-radio-group v-model="form.patentScope" size="medium">
                  <el-radio v-for="(item, index) in dict.type.sci_patent_scope" :key="index" :label="item.value"
                    :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否代理" prop="isAgency">
                <el-radio-group v-model="form.isAgency" size="medium">
                  <el-radio v-for="(item, index) in dict.type.sys_yes_no"
                  :key="index"
                  :label="item.label"
                  :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否PCT专利" prop="isPct">
                <el-radio-group v-model="form.isPct" size="medium">
                  <el-radio v-for="(item, index) in dict.type.sys_yes_no"
                  :key="index"
                  :label="item.label"
                  :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属项目" prop="projectId">
                <el-select v-model="form.projectId" placeholder="请选择所属项目" clearable :style="{width: '100%'}">

                <el-option
                  v-for="project in projectList"
                  :key="project.id"
                  :label="project.projectName"
                  :value="project.id"
                />
              </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider v-if="form.isAgency === '是'" ><i class="el-icon-user"></i>  代理信息</el-divider>
          <el-row :gutter="20" v-if="form.isAgency === '是'">
            <el-col :span="8">
              <el-form-item label="代理公司" prop="agencyCompany">
                <el-input v-model="form.agencyCompany" placeholder="请输入单行文本" clearable
                  :style="{width: '100%'}" maxlength=100></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="代理人" prop="agencyPerson">
                <el-input v-model="form.agencyPerson" placeholder="请输入代理人" clearable
                  :style="{width: '100%'}" maxlength=50></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人手机号" prop="agencyPhone">
                <el-input v-model="form.agencyPhone" placeholder="请输入手机号" :maxlength="11" show-word-limit clearable
                prefix-icon='el-icon-mobile' :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider  v-if="showFileUpload"><i class="el-icon-folder-opened"></i>  附件文档</el-divider>
          <file-upload-table v-if="showFileUpload" v-model="form.fileRows" :show-add="false"/>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <!-- 添加或修改科研专利信息对话框 -->
    <el-dialog :title="statusTitle" :visible.sync="openStatus" width="900px" append-to-body>
      <el-card shadow="always" style="margin-left: 20px;margin-right: 20px;">
        <el-form ref="formStatus" :model="formStatus" :rules="rules" size="medium" label-width="120px">
          <el-divider ><i class="el-icon-collection"></i>  状态信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="专利名称" prop="patentName">
                <el-input :disabled="true" v-model="formStatus.patentName" placeholder="请输入专利名称" clearable
                  :style="{width: '100%'}"
                  ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="专利申请号" prop="applicationNumber">
                <el-input :disabled="true" v-model="formStatus.applicationNumber" placeholder="请输入专利申请号" clearable
                  :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="专利状态" prop="applicationStatus">
                <el-radio-group v-model="formStatus.applicationStatus" size="medium">
                  <el-radio v-for="(status, index) in availableStatuses"
                  :key="index"
                  :label="status"
                  :disabled="index < currentIndex">{{status}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="变更时间" prop="authorizationDate">
                <el-date-picker v-model="formStatus.authorizationDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  :style="{width: '100%'}" placeholder="请输入变更时间" clearable></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider ><i class="el-icon-folder-opened"></i>  附件文档</el-divider>


          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="文件类型" required>
                <el-select  v-model="formStatus.fileRow.fileClassName" disabled placeholder="请选择文件名称" clearable :style="{width: '100%'}">
                  <el-option v-for="(item, optionIndex) in fileClassNameOptions" :key="optionIndex" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件" required>
                <file-upload v-model="formStatus.fileRow.fileInfo"
                @update:datetime="handleStatusDatetimeUpdate( $event)"/>
              </el-form-item>
            </el-col>

          </el-row>

        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="submitStatusForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-drawer
      title="专利信息"
      :visible.sync="drawer"
      size="50%">

      <el-card shadow="always"  style="margin-left: 20px;margin-right: 20px;">
        <div slot="header" >
          <span class="card-title">专利进度</span>

        </div>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in activities"
            :key="index"
            :icon="activity.icon"
            :type="activity.type"
            :color="activity.color"
            :size="activity.size"
            placement="top"
            :timestamp="activity.timestamp">
            <el-card>
              <h4>{{ activity.content }}</h4>
              <p>{{ activity.operator }}提交于 {{ activity.operateTime }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-card>

      <el-card shadow="always" style="margin: 20px;">
        <el-descriptions title="基本信息" border  :column="2">
          <el-descriptions-item label="专利名称"  > {{this.formView.patentName}}</el-descriptions-item>
          <el-descriptions-item label="研究方向">{{ getDeptLabel(formView.deptId) }}</el-descriptions-item>
          <el-descriptions-item label="专利类型">
            <dict-tag :options="dict.type.sci_palent_type" :value="formView.patentType"/>
          </el-descriptions-item>
          <el-descriptions-item label="专利状态">
            <dict-tag :options="dict.type.sci_ach_appl_status" :value="formView.applicationStatus"/>
          </el-descriptions-item>
          <el-descriptions-item label="申请人">
            {{this.formView.applicant}}
          </el-descriptions-item>
          <el-descriptions-item label="专利申请号">{{this.formView.applicationNumber}}</el-descriptions-item>
          <el-descriptions-item label="申请时间"  > {{this.formView.applicationDate}}</el-descriptions-item>

        </el-descriptions>
      </el-card>
      <el-card shadow="always" style="margin: 20px;">
        <el-descriptions title="详细信息" border  :column="2">


          <el-descriptions-item label="合作类型">
            <dict-tag :options="dict.type.sci_cooperation_type" :value="formView.cooperationType"/>
          </el-descriptions-item>
          <el-descriptions-item label="授权时间">{{this.formView.authorizationDate}}</el-descriptions-item>
          <el-descriptions-item label="统计年度"  > {{this.formView.statisticalYear}}</el-descriptions-item>
          <el-descriptions-item label="研究院署名">
            <dict-tag :options="dict.type.sci_signature" :value="formView.instituteSignature"/>
          </el-descriptions-item>
          <el-descriptions-item label="专利范围">
            <dict-tag :options="dict.type.sci_patent_scope" :value="formView.patentScope"/>
          </el-descriptions-item>
          <el-descriptions-item label="是否代理"  >
            <dict-tag :options="dict.type.sys_yes_no" :value="formView.isAgency"/>
          </el-descriptions-item>
          <el-descriptions-item label="是否PCT专利">
            <dict-tag :options="dict.type.sys_yes_no" :value="formView.isPct"/>
          </el-descriptions-item>
          <el-descriptions-item label="所属项目">

              {{ getProjectLabel(this.formView.projectId) }}
          </el-descriptions-item>



        </el-descriptions>
      </el-card>
      <el-card shadow="always" style="margin: 20px;">
        <el-descriptions title="代理信息" border :column="2">


          <el-descriptions-item label="代理公司"  > {{this.formView.agencyCompany}}</el-descriptions-item>
          <el-descriptions-item label="代理人">{{this.formView.agencyPerson}}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{this.formView.agencyPhone}}</el-descriptions-item>


        </el-descriptions>
      </el-card>


      <el-card shadow="always" style="margin: 20px;">
          <el-descriptions title="附件文档" :column="1" border>
          <el-descriptions-item v-for="(row, index) in formView.fileRows" :key="'file-' + index" :label="row.fileClassName || '未命名文件'">
            <div>



              <p>
                <template v-if="row.fileInfo && row.fileInfo.length > 0">
                  <div v-for="(file, fileIndex) in row.fileInfo" :key="fileIndex" style="margin-top: 5px;">
                    <el-link
                      type="primary"
                      target="_blank"
                       @click="handleDownload(file)"
                    >
                      {{ file.originalName }}
                    </el-link>

                    <span style="margin-left: 8px; color: #909399; font-size: 12px">
                      ({{ (file.fileSize/1024).toFixed(2) }} KB)
                    </span>
                  </div>
                </template>
                <span v-else style="color: #909399">无附件</span>


              </p>
              <p>上传人: {{ row.uploader }}</p>
              <p>上传时间: {{ row.uploadTime }}</p>

            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
    </el-drawer>



  </div>
</template>

<script>
import { listPatent, getPatent, delPatent, addPatent, updatePatent,updateStatus,getPatentCountByDept,getPatentCountByStatus } from "@/api/sci/patent";
import { listStatus_log} from "@/api/sci/status_log";
import * as echarts from 'echarts';
import { listDept } from '@/api/system/dept';
import { listProjectInfo } from '@/api/sci/projectInfo';
import { downloadMinioFile } from '@/api/common/common';
import FileUploadTable from '@/views/sci/components/FileUploadTable';
import { checkRole } from '@/utils/permission'

export default {
  name: "Patent",
  dicts: ['sys_yes_no','sci_year','sci_ach_appl_status', 'sci_palent_type','sci_cooperation_type','sci_signature','sci_patent_scope'],
  components: {
    FileUploadTable
  },
  data() {
    return {
      showFileUpload: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 科研专利信息表格数据
      patentList: [],
      // 弹出层标题
      title: "222",
      statusForm: {

      },
      statusTitle: "",
      // 是否显示弹出层
      open: false,
       // 是否显示弹出层
      openStatus: false,

      drawer: false,

      isAdding: false,
      // 联系电话时间范围
      daterangeApplicationDate: [],
      // 联系电话时间范围
      daterangeAuthorizationDate: [],
      username : this.$store.state.user.nickName,

      authorizationCount:0,
      applicationCount:0,
      acceptanceCount:0,

      authorizationCount2:0,
      applicationCount2:0,
      acceptanceCount2:0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        patentName: null,
        applicationStatus: null,
        deptId: null,
        patentType: null,
        applicationNumber: null,
        applicant: null,
        applicationDate: null,
        authorizationDate: null,
        cooperationType: null,
        statisticalYear: null,
        instituteSignature: null,
        patentScope: null,
        isPct: null,
      },
      projectList: [],
      deptList: [],

      activities: [],

      patentTypeToStatusMapping: {
        '新型实用专利': ['申请', '受理', '初审', '授权'],
        '外观专利': ['申请', '受理', '初审', '授权'],
        '发明专利': ['申请', '受理', '初审', '公布', '实审', '授权', '维持'],

      },


      statusToFileMapping: {
        '申请': ['专利代理协议'],
        '受理': ['专利代理协议', '受理通知书'],
        '初审': ['专利代理协议', '受理通知书', '初步审查合格通知书'],
        '公布': ['专利代理协议', '受理通知书', '初步审查合格通知书', '公布通知书'],
        '实审': ['专利代理协议', '受理通知书', '初步审查合格通知书', '公布通知书', '实质审查阶段通知书'],
        '授权': ['专利代理协议', '受理通知书', '初步审查合格通知书', '公布通知书', '实质审查阶段通知书', '授权通知书'],
        '维持': ['专利代理协议', '受理通知书', '初步审查合格通知书', '公布通知书', '实质审查阶段通知书', '授权通知书', '专利授权证书']
      },

      statusToFileMapping2: {
        '申请': '专利代理协议',
        '受理': '受理通知书',
        '初审': '初步审查合格通知书',
        '公布': '公布通知书',
        '实审': '实质审查阶段通知书',
        '授权': '授权通知书',
        '维持': '专利授权证书'
      },

      availableStatuses: [],


      // 表单参数
      form: {
        fileRows: [
          {
            fileClassName: '',
            uploader: '',
            uploadTime: '',
            fileInfo: []
          }
        ]
      },
      formStatus: {
        fileRow:
          {
            fileClassName: '',
            uploader: '',
            uploadTime:   '',
            fileInfo: []
          }

      },
      formView: {
        fileRows: [] // 初始化为空数组
      },
      currentStatus: '',
      // 表单校验
      rules: {
        patentName: [{
          required: true,
          message: '请输入专利名称',
          trigger: 'blur'
        }],
        deptId: [{
          required: true,
          message: '请输入研究方向',
          trigger: 'change'
        }],
        patentType: [{
          required: true,
          message: '专利类型不能为空',
          trigger: 'change'
        }],
        applicant: [{
          required: true,
          message: '请输入申请人',
          trigger: 'blur'
        }],
        applicationStatus: [{
          required: true,
          message: '专利状态不能为空',
          trigger: 'change'
        }],
        applicationNumber: [{
          required: true,
          message: '请输入专利申请号',
          trigger: 'blur'
        }],
        applicationDate: [{
          required: true,
          message: '请选择申请时间',
          trigger: 'blur'
        }],
         authorizationDate: [{
          validator: (rule, value, callback) => {
            if (value && this.form.applicationDate) {
              if (value <= this.form.applicationDate) {
                callback(new Error('授权时间必须晚于申请时间'));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: 'change'
        }],
        cooperationType: [{
          required: true,
          message: '合作类型不能为空',
          trigger: 'change'
        }],

        statisticalYear: [{
          required: true,
          message: '请输入统计年度',
          trigger: 'change'
        }],
        instituteSignature: [{
          required: true,
          message: '研究院署名不能为空',
          trigger: 'change'
        }],
        patentScope: [{
          required: true,
          message: '专利范围不能为空',
          trigger: 'change'
        }],
        isAgency: [{
          required: true,
          message: '是否代理不能为空',
          trigger: 'change'
        }],
        isPct: [{
          required: true,
          message: '是否PCT专利不能为空',
          trigger: 'change'
        },{
            validator: (rule, value, callback) => {
              const { patentScope } = this.form;

              if (patentScope === '国内' && value === '是') {
                callback(new Error('国内专利不允许设置为 PCT 专利'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        projectId: [],
        agencyCompany: [{
          required: true,
          message: '请输入单行文本',
          trigger: 'blur'
        }],
        agencyPerson: [{
          required: true,
          message: '请输入代理人',
          trigger: 'blur'
        }],
        agencyPhone: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        }, {
          pattern: /^1(3|4|5|7|8|9)\d{9}$/,
          message: '手机号格式错误',
          trigger: 'blur'
        }],
        fileRows: {
          fileClassName: [
            { required: true, message: '请选择文件名称', trigger: 'change' }
          ],

          fileInfo: [
            { required: true, message: '请上传附件', trigger: 'change' }
          ],
        },

        // 'fileRow.fileClassName': [{ required: true }],
        // 'fileRow.fileInfo': [{ required: true }]

      },

      statisticalYearOptions: [{
        "label": "2025",
        "value": "2025"
      }, {
        "label": "2024",
        "value": "2024"
      },{
        "label": "2023",
        "value": "2023"
      }, {
        "label": "2022",
        "value": "2022"
      }],
      fileClassNameOptions: [{
          "label": "专利代理协议",
          "value": "专利代理协议"
        }, {
          "label": "受理通知书",
          "value": "受理通知书"
        }, {
          "label": "初步审查合格通知书",
          "value": "初步审查合格通知书"
        }, {
          "label": "公布通知书",
          "value": "公布通知书"
        }, {
          "label": "实质审查阶段通知书",
          "value":  "实质审查阶段通知书"
        }, {
          "label": "授权通知书",
          "value": "授权通知书"
        }, {
          "label": "专利授权证书",
          "value": "专利授权证书"
        }
      ],

    };
  },
  created() {
    this.getList();
    this.getProjectList();
    this.getDeptList();
  },
  mounted() {
    // this.getList();
  },
  watch: {
    'form.patentType': function(newType) {
      if(this.isAdding){

        // Update available statuses based on the selected patent type
        if (this.patentTypeToStatusMapping[newType]) {
          this.availableStatuses = this.patentTypeToStatusMapping[newType];
          // Reset applicationStatus to the first available status
          this.form.applicationStatus = this.availableStatuses[0];
        } else {
          this.availableStatuses = [];
          this.form.applicationStatus = '';
        }
        if(this.statusToFileMapping = this.form.patentType ==='发明专利'){
          this.statusToFileMapping = {
            '申请': ['专利代理协议'],
            '受理': ['专利代理协议', '受理通知书'],
            '初审': ['专利代理协议', '受理通知书', '初步审查合格通知书'],
            '公布': ['专利代理协议', '受理通知书', '初步审查合格通知书', '公布通知书'],
            '实审': ['专利代理协议', '受理通知书', '初步审查合格通知书', '公布通知书', '实质审查阶段通知书'],
            '授权': ['专利代理协议', '受理通知书', '初步审查合格通知书', '公布通知书', '实质审查阶段通知书', '授权通知书'],
            '维持': ['专利代理协议', '受理通知书', '初步审查合格通知书', '公布通知书', '实质审查阶段通知书', '授权通知书', '专利授权证书']
          }
        } else {
          this.statusToFileMapping = {
          '申请': ['专利代理协议'],
          '受理': ['专利代理协议', '受理通知书'],
          '初审': ['专利代理协议', '受理通知书', '初步审查合格通知书'],
          '授权': ['专利代理协议', '受理通知书', '初步审查合格通知书', '授权通知书']
          }
        }
      }
    },
    'form.applicationStatus': function(newStatus) {


      if (newStatus === '授权') {
        this.$set(this.rules, 'authorizationDate', [
          { required: true, message: '请输入授权时间', trigger: 'change' }
        ]);
      } else {
        this.$set(this.rules, 'authorizationDate', []);
      }

      if(newStatus !==null && newStatus !==''){
        this.showFileUpload = true;
      }else{
        this.showFileUpload = false;
      }

      if(this.isAdding){
        if (this.statusToFileMapping[newStatus]) {

          const requiredFiles = this.statusToFileMapping[newStatus];
          this.form.fileRows = this.form.fileRows.filter(row => requiredFiles.includes(row.fileClassName));
          requiredFiles.forEach(fileName => {
            if (!this.form.fileRows.some(row => row.fileClassName === fileName)) {
              this.form.fileRows.push({
                fileClassName: fileName,
                uploader: this.username,
                uploadTime: '',
                fileInfo: []
              });
            }
          });
        } else {
          this.form.fileRows = [
            {
              fileClassName: '',
              uploader: this.username,
              uploadTime: '',
              fileInfo: []
            }
          ];
        }
      }
    },
    'formStatus.applicationStatus': function(newStatus) {
      this.$set(this.rules, 'authorizationDate', [
          { required: true, message: '请输入变更时间', trigger: 'change' }
        ]);
      if (this.statusToFileMapping2[newStatus]) {
        this.formStatus.fileRow.fileClassName = this.statusToFileMapping2[newStatus];
      } else {
        this.formStatus.fileRow.fileClassName = '';
      }
    },
    'form.patentScope'(newVal) {
      if (newVal === '国内') {
        this.form.isPct = '否'; // 国内专利 → 强制设为 否
        this.$message.info('国内专利不允许设置为 PCT 专利');
      }
    },
    'form.isAgency': function(newVal) {
      if (newVal !== '是') {
        this.form.agencyCompany = '';
        this.form.agencyPerson = '';
        this.form.agencyPhone = '';
      }
    },
    'form.applicationDate': {
      handler(newVal) {
        this.$nextTick(() => {
          if (this.$refs.form && this.form.authorizationDate) {
            this.$refs.form.validateField('authorizationDate');
          }
        });
      },
      immediate: false
    },
    'form.authorizationDate': {
      handler(newVal) {
        this.$nextTick(() => {
          if (this.$refs.form && this.form.applicationDate && newVal) {
            this.$refs.form.validateField('authorizationDate');
          }
        });
      },
      immediate: false
    }
  },
  computed: {
    currentIndex() {
      return this.availableStatuses.findIndex(
        item => item === this.currentStatus
      );
    }
  },
  methods: {
     // 根据角色判断是否显示
    hasRole(requiredRoles) {
      return checkRole(requiredRoles)
    },
    /** 查询科研专利信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeApplicationDate && '' != this.daterangeApplicationDate) {
        this.queryParams.params["beginApplicationDate"] = this.daterangeApplicationDate[0];
        this.queryParams.params["endApplicationDate"] = this.daterangeApplicationDate[1];
      }
      if (null != this.daterangeAuthorizationDate && '' != this.daterangeAuthorizationDate) {
        this.queryParams.params["beginAuthorizationDate"] = this.daterangeAuthorizationDate[0];
        this.queryParams.params["endAuthorizationDate"] = this.daterangeAuthorizationDate[1];
      }
      listPatent(this.queryParams).then(response => {
        this.patentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openStatus = false;
      this.reset();
      this.resetStatus();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        patentName: null,
        applicationStatus: null,
        deptId: null,
        patentType: null,
        applicationNumber: null,
        applicant: null,
        applicationDate: null,
        authorizationDate: null,
        cooperationType: null,
        statisticalYear: null,
        instituteSignature: null,
        patentScope: null,
        isAgency: null,
        isPct: null,
        agencyCompany: null,
        agencyPerson: null,
        agencyPhone: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        fileRows: [  // 保持基础结构
          {
            fileClassName: '',
            uploader: '',
            uploadTime: '',
            fileInfo: []
          }
        ]
      };
      this.resetForm("form");
    },
    resetStatus() {
      this.formStatus = {
        id: null,
        projectId: null,
        patentName: null,
        applicationStatus: null,
        deptId: null,
        patentType: null,
        applicationNumber: null,
        applicant: null,
        applicationDate: null,
        authorizationDate: null,
        cooperationType: null,
        statisticalYear: null,
        instituteSignature: null,
        patentScope: null,
        isAgency: null,
        isPct: null,
        agencyCompany: null,
        agencyPerson: null,
        agencyPhone: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        fileRow:   // 保持基础结构
          {
            fileClassName: '',
            uploader: '',
            uploadTime: '',
            fileInfo: []
          }

      }
      this.resetForm("formStatus");
    },
    resetView() {
      this.formView = {
        id: null,
        projectId: null,
        patentName: null,
        applicationStatus: null,
        deptId: null,
        patentType: null,
        applicationNumber: null,
        applicant: null,
        applicationDate: null,
        authorizationDate: null,
        cooperationType: null,
        statisticalYear: null,
        instituteSignature: null,
        patentScope: null,
        isAgency: null,
        isPct: null,
        agencyCompany: null,
        agencyPerson: null,
        agencyPhone: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        fileRow:   // 保持基础结构
          {
            fileClassName: '',
            uploader: '',
            uploadTime: '',
            fileInfo: []
          }

      }
    },
    handleDatetimeUpdate(index, datetime) {
      // Update the corresponding uploadTime field
      this.$set(this.form.fileRows[index], 'uploadTime', datetime);
    },
    handleStatusDatetimeUpdate(datetime) {
      // Update the corresponding uploadTime field
      this.$set(this.formStatus.fileRow, 'uploadTime', datetime);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeApplicationDate = [];
      this.daterangeAuthorizationDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isAdding=true;
      this.availableStatuses=[],
      this.title = "添加科研专利信息";
      this.form.fileRows[0].uploader = this.username;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPatent(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.isAdding=false;
        this.availableStatuses=['申请', '受理', '初审', '公布', '实审', '授权', '维持'],
        this.title = "修改科研专利信息";
      });
    },
    handleView(row) {
      this.resetView();
      const id = row.id || this.ids
      getPatent(id).then(response => {

        if (response.data && response.data.fileRows) {
          response.data.fileRows = response.data.fileRows.map(fileRow => {
            try {
              // 如果fileInfo是字符串则转换为数组，否则保持原样
              fileRow.fileInfo = typeof fileRow.fileInfo === 'string'
                ? JSON.parse(fileRow.fileInfo)
                : fileRow.fileInfo;
            } catch (e) {
              console.error('fileInfo解析失败：', e);
              fileRow.fileInfo = [];
            }
            return fileRow;
          });
        }
        this.formView = response.data;

        const query = {
          entityType: 'SciPatentInfo', // Entity type, e.g., 'patent'
          entityId: id, // Entity ID, e.g., patent ID
          statusField: 'applicationStatus' // Status field to query
        };
        listStatus_log(query).then(logResponse => {
          this.activities = logResponse.rows.map(item => ({
            content: item.newStatus, // Status description from the API response
            timestamp: this.parseTime(item.statusTime, '{y}-{m}-{d}'),
            operator: item.operator, // Operator from the API response
            operateTime: item.operateTime, // Operator from the API response
            icon: 'el-icon-check', // Default icon
            type: 'primary', // Default type
            color: '#0bbd87', // Default color
            size: 'large' // Default size
          }));
        }).catch(error => {
          console.error('获取状态日志失败：', error);
          this.$message.error('无法加载状态日志');
        });

        console.log(this.activities)


        this.drawer = true;
      });
    },

    parseTime(time, format = '{y}-{m}-{d} {h}:{i}:{s}') {
      if (!time) return '';
      let date = new Date(time);
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds()
      };
      return format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
        return value.toString().padStart(2, '0');
      });
    },
    handleDownload(file) {
      const fileName = file.url; // 替换为实际的文件名
      downloadMinioFile(fileName);
    },

    handleStatusUpdate(row) {
      this.resetStatus();
      const id = row.id || this.ids
      getPatent(id).then(response => {
        const data = response.data;


        // 获取专利类型
        const patentType = data.patentType;

        // 根据专利类型设置可用状态
        if (this.patentTypeToStatusMapping[patentType]) {
          this.availableStatuses = this.patentTypeToStatusMapping[patentType];
          // 默认选择第一个状态
          // this.formStatus.applicationStatus = this.availableStatuses[0];
        } else {
          this.availableStatuses = [];
          this.formStatus.applicationStatus = '';
        }

        this.formStatus.id = data.id;
        this.formStatus.patentName = data.patentName;
        this.formStatus.applicationNumber = data.applicationNumber;


        this.currentStatus= data.applicationStatus

        this.openStatus = true;
        this.statusTitle = "专利状态变更";
        this.formStatus.fileRow.uploader = this.username;
      });
    },
    /** 提交按钮 */
    submitForm() {
      // 检查 fileRows 中的 fileInfo 是否都已上传
      const isAllFilesUploaded = this.form.fileRows.every(row => {
        if (!row.fileInfo) return false;

        try {
          const files = typeof row.fileInfo === 'string' ? JSON.parse(row.fileInfo) : row.fileInfo;
          return Array.isArray(files) && files.length > 0;
        } catch (e) {
          console.error('fileInfo 解析失败:', e);
          return false;
        }
      });

      if (!isAllFilesUploaded) {
        this.$message.error('请确保每个文件都上传了附件');
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 增加额外的时间关系验证保险
          if (this.form.authorizationDate && this.form.applicationDate &&
              this.form.authorizationDate <= this.form.applicationDate) {
            this.$message.error('授权时间必须晚于申请时间');
            return;
          }
          // 去除表单中所有字符串字段的前后空格
          const trimmedForm = this.trimFormFields(this.form);
          if (this.form.id != null) {
            updatePatent(trimmedForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPatent(trimmedForm).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })

          }
        }
      });
    },

    submitStatusForm() {
      this.$refs["formStatus"].validate(valid => {
        if (valid) {
          // 提交前检查文件是否已上传
          const fileInfo = typeof this.formStatus.fileRow.fileInfo === 'string' ? JSON.parse(this.formStatus.fileRow.fileInfo) : this.formStatus.fileRow.fileInfo;
          if (!fileInfo || !Array.isArray(fileInfo) || fileInfo.length === 0) {
            this.$modal.msgError("请先上传附件");
            return;
          }
          const trimmedForm = this.trimFormFields(this.formStatus);
          if (trimmedForm.id!= null) {
            updateStatus(trimmedForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openStatus = false;
              this.getList();
            });
          }
        }
      })
    },

     // 去除表单字段前后空格的方法
    trimFormFields(form) {
      const trimmedForm = { ...form };
      for (const key in trimmedForm) {
        if (typeof trimmedForm[key] === 'string') {
          trimmedForm[key] = trimmedForm[key].trim();
        }
      }
      return trimmedForm;
    },
    getProjectLabel(projectId) {
      const project = this.projectList.find(p => p.id === projectId);
      return project ? project.projectName : '';
    },

    getDeptLabel(deptId) {
      const dept = this.deptList.find(d => d.deptId === deptId);
      return dept ? dept.deptName : '';
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const name=row.patentName;
      this.$modal.confirm('是否确认删除科研专利名为"' + name + '"的数据项？').then(function() {
        return delPatent(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/patent/export', {
        ...this.queryParams
      }, `patent_${new Date().getTime()}.xlsx`)
    },

    getProjectList() {
      listProjectInfo().then(response => {
        this.projectList = response.rows;
      });
    },
    getDeptList() {
      listDept().then(response => {
        this.deptList = response.data.filter(dept => dept.deptId !== 100);      });
    },

    addRow() {

      this.form.fileRows.push({
        fileClassName: '',
        uploader: this.username,
        uploadTime: '',
        fileInfo: [],
      });
    },
    removeRow(index) {
      if (this.form.fileRows.length > 1) {
        this.form.fileRows.splice(index, 1);
      } else {
        this.$message.warning('至少需要保留一行');
      }
    },

    async initPieChart() {
      try {
        const pieChart = echarts.init(this.$refs.pieChart);

        // 调用接口获取专利状态统计
        const response = await getPatentCountByStatus(); // 假设该接口返回的数据结构为 [{ status: '申请', count: 10 }, ...]
        const data = response.data || [];

        const statusCounts = data.reduce((acc, item) => {
          if (item.status === '申请') acc.applicationCount = item.totalcount;
          if (item.status === '受理') acc.acceptanceCount = item.totalcount;
          if (item.status === '授权') acc.authorizationCount = item.totalcount;
          return acc;
        }, {
          applicationCount: 0,
          acceptanceCount: 0,
          authorizationCount: 0
        });

        // 将结果赋值给 Vue 实例的 data 属性
        this.applicationCount = statusCounts.applicationCount;
        this.acceptanceCount = statusCounts.acceptanceCount;
        this.authorizationCount = statusCounts.authorizationCount;

        // 将原始数据映射为 ECharts 需要的格式：{ value: count, name: status }
        const seriesData = data.map(item => ({
          value: item.totalcount,
          name: item.status
        }));

        const pieOption = {
          title: {
            text: '总计专利状态分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)' // 更直观显示百分比
          },
          // legend: {
          //   orient: 'vertical',
          //   left: 'left',
          //   top: 'center'
          // },
          series: [
            {
              name: '专利状态',
              type: 'pie',
              // radius: ['40%', '70%'],
              center: ['50%', '60%'],
              data: seriesData, // 使用动态数据
               label: {
                // show: false // 隐藏饼图上的标签
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ],
          graphic: {
            type: 'text',
            left: 'center',
            top: 'center',

          }
        };

        pieChart.setOption(pieOption, true);
      } catch (error) {
        console.error('加载饼图失败:', error);
        this.$message.error('无法加载专利状态数据');
      }
    },

    async initPieChart2() {
      try {
        const pieChart = echarts.init(this.$refs.pieChart2);

        // 调用接口获取专利状态统计
        const response = await getPatentCountByStatus(); // 假设该接口返回的数据结构为 [{ status: '申请', count: 10 }, ...]
        const data = response.data || [];

        const statusCounts = data.reduce((acc, item) => {
          if (item.status === '申请') acc.applicationCount = item.currentcount;
          if (item.status === '受理') acc.acceptanceCount = item.currentcount;
          if (item.status === '授权') acc.authorizationCount = item.currentcount;
          return acc;
        }, {
          applicationCount: 0,
          acceptanceCount: 0,
          authorizationCount: 0
        });

        // 将结果赋值给 Vue 实例的 data 属性
        this.applicationCount2 = statusCounts.applicationCount;
        this.acceptanceCount2 = statusCounts.acceptanceCount;
        this.authorizationCount2 = statusCounts.authorizationCount;

        // 将原始数据映射为 ECharts 需要的格式：{ value: count, name: status }
        const seriesData = data.map(item => ({
          value: item.currentcount,
          name: item.status
        }));

        const pieOption = {
          title: {
            text: '本年专利状态分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)' // 更直观显示百分比
          },
          // legend: {
          //   // orient: 'vertical',
          //   left: 'left',

          //   top: 'bottom'
          // },
          series: [
            {
              name: '专利状态',
              type: 'pie',
              // radius: ['40%', '70%'],
              center: ['50%', '60%'],
              data: seriesData, // 使用动态数据
               label: {
                // show: false // 隐藏饼图上的标签
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ],
          graphic: {
            type: 'text',
            left: 'center',
            top: 'center',

          }
        };

        pieChart.setOption(pieOption, true);
      } catch (error) {
        console.error('加载饼图失败:', error);
        this.$message.error('无法加载专利状态数据');
      }
    },

    async initBarChart() {
      try {
        const deptMapping = {
        '能源战略与碳中和路径方向': '能源战略',
        '智慧矿山方向': '智慧矿山',
        '新型储能方向': '新型储能',
        '分布式能源方向': '分布式能源',
        '地下清洁能源资源方向': '地清',
        '二氧化碳捕集利用与封存方向': 'CCUS',
        '节能减碳方向': '节能减碳',
        '能源大数据方向': '能源大数据',
        '能源软件平台方向': '能源软件'
      };
        const response = await getPatentCountByDept();
        const data = response.data;

        // 提取 X 轴（部门名称）并进行映射转换
        const xAxisData = data.map(item => deptMapping[item.dept_name] || item.dept_name);
        // 提取两个系列的数据
        const totalData = data.map(item => item.patent_count_total); // 总量
        const yearData = data.map(item => item.patent_count_current_year);   // 本年度数量

        const barChart = echarts.init(this.$refs.barChart);
        const barOption = {
          title: {
            text: '九大方向专利数量',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: (params) => {
              return `${params[0].name}<br/>` +
                    `总量：${params[0].value} 项<br/>` +
                    `本年：${params[1].value} 项`;
            }
          },
          legend: {
            data: ['总量', '本年'],
             orient: 'vertical',
            left: 'left',
            top: 'top'
          },
          xAxis: {
            type: 'category',
            data: xAxisData,
            axisLabel: {
              fontSize: 8, // 设置字体大小
              color: '#666', // 设置字体颜色
              rotate: 45,


            }
          },
          yAxis: {
            type: 'value',
            minInterval: 1, // 设置最小刻度为1（整数）
          },
          grid: {
            left: '12%',
            right: '4%',
            bottom: '1%',
            containLabel: true
          },
          series: [

             {
              name: '总量',
              type: 'bar',
              barWidth: '40%',
              itemStyle: { color: '#5470C6' },
              data: totalData
            },
            {
              name: '本年',
              type: 'bar',
              barWidth: '40%',
              itemStyle: { color: '#91CC75' },
              data: yearData
            }
          ]
        };

        barChart.setOption(barOption, true); // 使用 true 表示合并配置
      } catch (error) {
        console.error('获取专利数量失败:', error);
        this.$message.error('无法加载部门专利数量');
      }
    }
  }
};
</script>


<style scoped>
.chart-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.center-button {
  display: flex;
  justify-content: center;
}

.card-title {
  font-family: SimHei, sans-serif;
  font-weight: bold;
}

.pie-and-status-wrapper {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  width: 100%;
}

.status-container {
  width: 60%;
  height: 200px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.status-label {
  color: #909399; /* 浅灰色 */
  font-size: 16px; /* 放大字体 */
  margin-bottom: 8px;
}

.status-count {
  color: #4985fc; /* 浅灰色 */
  font-size: 40px; /* 放大字体 */
  font-weight: bold;
}
.el-table__row .cell {
  text-align: center;
}


</style>
